package com.atguigu.Sink;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.been.WaterSensor;
import com.mysql.jdbc.Driver;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.connector.jdbc.JdbcConnectionOptions;
import org.apache.flink.connector.jdbc.JdbcExecutionOptions;
import org.apache.flink.connector.jdbc.JdbcSink;
import org.apache.flink.connector.jdbc.JdbcStatementBuilder;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * @author wky
 * @create 2021-07-14-20:53
 */
public class Sink_Jdbc {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment senv = StreamExecutionEnvironment.getExecutionEnvironment();
        DataStreamSource<String> source = senv.socketTextStream("hadoop102", 9998);
        SingleOutputStreamOperator<WaterSensor> map = source.map(new MapFunction<String, WaterSensor>() {
            @Override
            public WaterSensor map(String s) throws Exception {
                String[] split = s.split(",");
                WaterSensor waterSensor = new WaterSensor(split[0], Long.parseLong(split[1]), Integer.parseInt(split[2]));
                return waterSensor;
            }
        });

        map.addSink(JdbcSink.sink("insert into sensor values(?,?,?)", new JdbcStatementBuilder<WaterSensor>() {
            @Override
            public void accept(PreparedStatement ps, WaterSensor waterSensor) throws SQLException {
                ps.setString(1,waterSensor.getId());
                ps.setLong(2,waterSensor.getTs());
                ps.setInt(3,waterSensor.getVc());
            }}, //TODO 读取无界流时，指定条数，达到这个数据条数，则把数据写入Mysql
              JdbcExecutionOptions.builder().withBatchSize(1).build(),
                //TODO 读取无界流时，指定间隔时间，达到这个时间，则把数据写入Mysql
               // JdbcExecutionOptions.builder().withBatchIntervalMs(1000).build(),

                new JdbcConnectionOptions.JdbcConnectionOptionsBuilder()
                        .withUrl("jdbc:mysql://hadoop102:3306/test?useSSL=false")
                        .withUsername("root")
                        .withDriverName(Driver.class.getName())
                        .withPassword("123456")
                        .build()
        ));
        senv.execute();

    }
}
